package org.forwhat.advice;

import org.apache.ibatis.session.SqlSession;
import org.forwhat.framework.AOPChain;
import org.forwhat.framework.annotation.advisor.After;
import org.forwhat.framework.annotation.advisor.Around;
import org.forwhat.framework.aop.Advice.AfterAdvice;
import org.forwhat.framework.aop.Advice.AroundAdvice;
import org.forwhat.service.Impl.WhatPostServiceImpl;
import org.forwhat.util.SqlSessionUtilities;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Around("SqlSessionUpdateAdvice")
public class SqlSessionUpdateAdvice implements AroundAdvice {
    @Override
    public Object around(Method method, Object[] args, Object target) throws InvocationTargetException, IllegalAccessException {

//        设置一个循环剥离代理类
        Object trueTarget = target;
        int count = 0;
        while (trueTarget instanceof AOPChain){
            trueTarget = ((AOPChain) target).getTarget();
            count++;
        }

        Field[] declaredFields = trueTarget.getClass().getDeclaredFields();

//        同线程就是同一个
        SqlSession sqlSession = SqlSessionUtilities.openSqlSession();

        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
            Object mapper = sqlSession.getMapper(declaredField.getType());

            declaredField.setAccessible(true);
            declaredField.set(trueTarget,mapper);
            declaredField.setAccessible(false);
        }
        return method.invoke(target, args);
    }
}
